import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

void main() async {
  // 确保Flutter初始化完成（Flutter Web中可忽略空安全检查）
  await WidgetsFlutterBinding.ensureInitialized(); // 明确使用 await，避免警告

  // 初始化时区数据
  tz.initializeTimeZones(); // 无需 await，因该方法返回 void

  runApp(const TimeZoneDemoApp());
}

class TimeZoneDemoApp extends StatelessWidget {
  const TimeZoneDemoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '时区计算演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const TimeZoneDemoScreen(),
    );
  }
}

class TimeZoneDemoScreen extends StatefulWidget {
  const TimeZoneDemoScreen({super.key});

  @override
  State<TimeZoneDemoScreen> createState() => _TimeZoneDemoScreenState();
}

class _TimeZoneDemoScreenState extends State<TimeZoneDemoScreen> {
  List<TimeZoneInfo> _timeZoneData = [];
  bool _isLoading = false;
  final ScrollController _scrollController = ScrollController();
  int _daysOffset = 3; // 默认偏移3天

  @override
  void initState() {
    super.initState();
    _loadTimeZoneData();
  }

  // 加载时区数据
  Future<void> _loadTimeZoneData() async {
    setState(() {
      _isLoading = true;
      _timeZoneData = [];
    });

    try {
      // 定义各时区的位置
      final locations = {
        '中国 (Asia/Shanghai)': tz.getLocation('Asia/Shanghai'),
        '美国 (America/New_York)': tz.getLocation('America/New_York'),
        '埃及 (Africa/Cairo)': tz.getLocation('Africa/Cairo'),
        '英国 (Europe/London)': tz.getLocation('Europe/London'),
        'UTC': null,
      };

      // 获取当前 UTC 时间
      final utcNow = DateTime.now().toUtc();

      // 计算偏移后的 UTC 时间
      final utcOffsetTime = utcNow.add(Duration(days: _daysOffset));

      // 生成时区数据
      final data = <TimeZoneInfo>[];
      locations.forEach((label, location) {
        final nowFormatted = _formatDateTimeWithTimeZone(utcNow, location);
        final offsetFormatted = _formatDateTimeWithTimeZone(
          utcOffsetTime,
          location,
        );
        data.add(TimeZoneInfo(label, nowFormatted, offsetFormatted));
      });

      setState(() {
        _timeZoneData = data;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('加载时区数据失败: $e')));
    }
  }

  // 格式化日期时间
  String _formatDateTimeWithTimeZone(DateTime dateTime, tz.Location? location) {
    if (location == null) {
      // 直接格式化 UTC 时间
      return DateFormat('yyyy-MM-dd HH:mm:ss \'UTC\'').format(dateTime);
    } else {
      // 将 UTC 时间转换为指定时区的时间
      final tzDateTime = tz.TZDateTime.from(dateTime, location);
      return DateFormat('yyyy-MM-dd HH:mm:ss z').format(tzDateTime);
    }
  }

  // 更新天数偏移 - 参数类型为 double
  void _updateDaysOffset(double value) {
    final intValue = value.toInt();
    if (intValue != _daysOffset) {
      setState(() {
        _daysOffset = intValue;
      });
      _loadTimeZoneData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('时区计算演示'), centerTitle: true),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 天数偏移选择器
            Card(
              elevation: 4,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '选择天数偏移:',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Slider(
                      value: _daysOffset.toDouble(),
                      min: 1,
                      max: 10,
                      divisions: 9,
                      label: '$_daysOffset 天',
                      onChanged: _updateDaysOffset,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: const [Text('1天'), Text('10天')],
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 加载状态
            if (_isLoading)
              const Center(child: CircularProgressIndicator())
            else
              Expanded(
                child: ListView.builder(
                  controller: _scrollController,
                  itemCount: _timeZoneData.length,
                  itemBuilder: (context, index) {
                    final info = _timeZoneData[index];
                    return Card(
                      elevation: 2,
                      margin: const EdgeInsets.symmetric(vertical: 8),
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              info.label,
                              style: const TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            // 移除 Divider 的 const 关键字
                            Divider(height: 20), // 原为 const Divider(height: 20)
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  '当前时间:',
                                  style: TextStyle(fontWeight: FontWeight.bold),
                                ),
                                const SizedBox(width: 10),
                                Expanded(
                                  child: SelectableText(info.currentTime),
                                ),
                              ],
                            ),
                            const SizedBox(height: 8),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '${_daysOffset}天后:',
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(width: 10),
                                Expanded(
                                  child: SelectableText(info.offsetTime),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),

            const SizedBox(height: 16),

            // 说明文本
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Text(
                '时区计算说明:\n'
                '1. 所有时间计算基于 UTC 时间，避免夏令时影响\n'
                '2. 拖动滑块可调整天数偏移量\n'
                '3. 点击时间文本可复制\n'
                '4. 时区信息自动更新，反映当前实际时差',
                style: TextStyle(fontSize: 14),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 时区信息模型
class TimeZoneInfo {
  final String label;
  final String currentTime;
  final String offsetTime;

  TimeZoneInfo(this.label, this.currentTime, this.offsetTime);
}
